package com.formiaomiao.demain.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.formiaomiao.demain.R;
import com.formiaomiao.demain.adapter.ReplaceBackgroundAdapter;
import com.formiaomiao.demain.base.BaseApplication;
import com.formiaomiao.demain.base.BaseUrl;
import com.formiaomiao.demain.db.IsPushBean;
import com.formiaomiao.demain.greendao.IsPushBeanDao;
import com.formiaomiao.demain.model.ReplaceBackgroundBean;
import com.formiaomiao.demain.util.MessageEvent;
import com.formiaomiao.demain.util.SpacesItemDecoration;
import com.formiaomiao.demain.util.StaticValues;
import com.formiaomiao.demain.weight.LoadingDialog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ReplaceBackgroundActivity extends PicActivity {

    @BindView(R.id.iv_class_back)
    ImageView ivClassBack;
    @BindView(R.id.tv_class_name)
    TextView tvClassName;
    @BindView(R.id.tv_replace_background)
    TextView tvReplaceBackground;
    @BindView(R.id.tv_recovery_background)
    TextView tvRecoveryBackground;
    @BindView(R.id.rl_bg)
    RecyclerView rlBg;

    IsPushBeanDao isPushBeanDao;
    IsPushBean pushBean = new IsPushBean();
    LoadingDialog loadingDialog;

    ReplaceBackgroundAdapter adapter;
    List<ReplaceBackgroundBean.DataBean> list = new ArrayList<>();
    ReplaceBackgroundBean backgroundBean = new ReplaceBackgroundBean();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_replace_background);
        ButterKnife.bind(this);
        ViewInit();
    }

    private void ViewInit() {
        loadingDialog = new LoadingDialog(this);
        tvClassName.setText("修改聊天背景图片");
        int verticalSpacing = getResources().getDimensionPixelSize(R.dimen.vertical);
        int horizontalSpacing = getResources().getDimensionPixelSize(R.dimen.horizontal);
        isPushBeanDao = BaseApplication.getInstances().getDaoSession().getIsPushBeanDao();
        rlBg.setLayoutManager(new GridLayoutManager(this, 2));
        rlBg.addItemDecoration(new SpacesItemDecoration(verticalSpacing, horizontalSpacing));
        adapter = new ReplaceBackgroundAdapter(list, this);
        rlBg.setAdapter(adapter);
        adapter.setOnItemClickListener(new ReplaceBackgroundAdapter.onItemClickListener() {
            @Override
            public void itemClickListener(View v, int i) {
                if (list.get(i).isHavefile()) {
                    pushBean = isPushBeanDao.queryBuilder().where(IsPushBeanDao.Properties.ChatMsgId.
                            eq(StaticValues.username + "#" +
                                    getIntent().getStringExtra("username"))).unique();
                    if (pushBean == null) {
                        pushBean = new IsPushBean();
                        pushBean.setChatMsgId(StaticValues.username + "#" +
                                getIntent().getStringExtra("username"));
                        pushBean.setId(null);
                        pushBean.setIspush(false);
                        pushBean.setBgpath(Environment.getExternalStorageDirectory() + "/demain/chat/" + list.get(i).getImgname());
                        isPushBeanDao.insert(pushBean);
                    } else {
                        pushBean.setChatMsgId(StaticValues.username + "#" +
                                getIntent().getStringExtra("username"));
                        pushBean.setBgpath(Environment.getExternalStorageDirectory() + "/demain/chat/" + list.get(i).getImgname());
                        isPushBeanDao.update(pushBean);
                    }
                    EventBus.getDefault().post(new MessageEvent("修改背景"));
                    finish();
                    ChatSettingsActivity.getInstances().finish();
                } else {
                    downloadFile(ReplaceBackgroundActivity.this,
                            list.get(i).getImgurl(),
                            Environment.getExternalStorageDirectory() + "/demain/chat/",
                            list.get(i).getImgname(),
                            list.get(i).getImgurl(), i);
                }
            }
        });
        PicDataInit();
    }

    @Override
    public void formAlbum(String path) {
        ReplaceBackInit(path);
    }

    @Override
    public void formCamera(String path) {
        ReplaceBackInit(path);
    }

    @Override
    public void formCorp(String path) {
        ReplaceBackInit(path);
    }

    private void ReplaceBackInit(String path) {
        pushBean = isPushBeanDao.queryBuilder().where(IsPushBeanDao.Properties.ChatMsgId.
                eq(StaticValues.username + "#" +
                        getIntent().getStringExtra("username"))).unique();
        if (pushBean == null) {
            pushBean = new IsPushBean();
            pushBean.setChatMsgId(StaticValues.username + "#" +
                    getIntent().getStringExtra("username"));
            pushBean.setId(null);
            pushBean.setIspush(false);
            pushBean.setBgpath(path);
            isPushBeanDao.insert(pushBean);
        } else {
            pushBean.setChatMsgId(StaticValues.username + "#" +
                    getIntent().getStringExtra("username"));
            pushBean.setBgpath(path);
            isPushBeanDao.update(pushBean);
        }
        EventBus.getDefault().post(new MessageEvent("修改背景"));
        finish();
        ChatSettingsActivity.getInstances().finish();
    }

    private void PicDataInit() {
        loadingDialog.show();
        OkGo.<String>post(BaseUrl.SELECTPICBG).tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (response.body().contains("200")) {
                    backgroundBean = gson.fromJson(response.body(), ReplaceBackgroundBean.class);
                    list.addAll(backgroundBean.getData());
                    pushBean = isPushBeanDao.queryBuilder().where(IsPushBeanDao.Properties.ChatMsgId.
                            eq(StaticValues.username + "#" +
                                    getIntent().getStringExtra("username"))).unique();
                    String path = pushBean.getBgpath();
                    if(path.contains("demain/chat")){
                        adapter.setSelectedPosition(Integer.parseInt(new File(path).getName().split("\\.")[0])-1);
                    }
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                loadingDialog.dismiss();
            }
        });
    }

    /**
     * @param context          上下文
     * @param fileUrl          下载完整url
     * @param destFileDir      SD路径
     * @param destFileName     文件名
     * @param mFileRelativeUrl 下载相对地址
     *                         （我们从服务器端获取到的数据都是相对的地址）例如： "filepath": "/movie/20180511/1526028508.txt"
     */
    public void downloadFile(Context context, String fileUrl, String destFileDir,
                             final String destFileName, String mFileRelativeUrl, final int index) {
        String mDestFileName = destFileName.split("\\.")[0] + mFileRelativeUrl.substring(mFileRelativeUrl.lastIndexOf("."), mFileRelativeUrl.length());
        OkGo.<File>get(fileUrl).tag(context).execute(new FileCallback(destFileDir, mDestFileName) { //文件下载时指定下载的路径以及下载的文件的名称
            @Override
            public void onStart(Request<File, ? extends Request> request) {
                super.onStart(request);
                loadingDialog.show();
            }

            @Override
            public void onSuccess(com.lzy.okgo.model.Response<File> response) {
                adapter.setSelectedPosition(index);
                adapter.notifyDataSetChanged();
                pushBean = isPushBeanDao.queryBuilder().where(IsPushBeanDao.Properties.ChatMsgId.
                        eq(StaticValues.username + "#" +
                                getIntent().getStringExtra("username"))).unique();
                if (pushBean == null) {
                    pushBean = new IsPushBean();
                    pushBean.setChatMsgId(StaticValues.username + "#" +
                            getIntent().getStringExtra("username"));
                    pushBean.setId(null);
                    pushBean.setIspush(false);
                    pushBean.setBgpath(Environment.getExternalStorageDirectory() + "/demain/chat/" + list.get(index).getImgname());
                    isPushBeanDao.insert(pushBean);
                } else {
                    pushBean.setChatMsgId(StaticValues.username + "#" +
                            getIntent().getStringExtra("username"));
                    pushBean.setBgpath(Environment.getExternalStorageDirectory() + "/demain/chat/" + list.get(index).getImgname());
                    isPushBeanDao.update(pushBean);
                }
                EventBus.getDefault().post(new MessageEvent("修改背景"));
                finish();
                ChatSettingsActivity.getInstances().finish();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                loadingDialog.dismiss();
            }

            @Override
            public void onError(com.lzy.okgo.model.Response<File> response) {
                super.onError(response);
                Log.e("DownLoadFileUtils", "下载文件出错" + "DDDDD" + response.message());
            }

            @Override
            public void downloadProgress(Progress progress) {
                super.downloadProgress(progress);
                float dLProgress = progress.fraction;
                Log.e("DownLoadFileUtils", "文件下载的进度" + "DDDDD" + dLProgress);
            }
        });
    }

    @OnClick({R.id.iv_class_back, R.id.tv_replace_background, R.id.tv_recovery_background})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_class_back:
                finish();
                break;
            case R.id.tv_replace_background:
                showPicPopWindow(tvReplaceBackground, "/demain/img/", false);
                break;
            case R.id.tv_recovery_background:
                ReplaceBackInit("");
                break;
        }
    }
}
